﻿var CompanyConnectionPage = function(pageContainer, companies, authData) {
    var self = this;

    self.AuthData = authData;

    self.Companies = new Array();

    CompanyConnectionPage.superclass.constructor.call(this, pageContainer);

    var connected = false;

    var Elements = {
        companiesList: pageContainer.find(".companiesList"),
        title: pageContainer.find(".title1"),
        pagetitle: pageContainer.find('.pagetitle')
    };

    var Templates = {
        companyTemplate: pageContainer.find("#companyTemplate")
    };

    self.initialize = override(self.initialize, function() {
        app.translatePage(app.Pages.CompanyConnection);

        self.Companies = companies;
        app.User.Companies = companies;

        if (companies.length > 1) {
            Elements.pagetitle.show();
            var source = Templates.companyTemplate.html();
            var template = Handlebars.compile(source);

            var html = "";
            for (var i = 0; i < companies.length; i++) {
                var c = companies[i];
                c.POZA = c.ImageUrl != null && c.ImageUrl.length ? c.ImageUrl : Utils.defaultCompanyPhotoPath;
                html += template(c);
            }
            Elements.companiesList.html(html);
            Elements.companiesList.find(".company:first").addClass("company-1st");
            Elements.companiesList.find(".company").tap(function(e) {
                var index = Elements.companiesList.children().index($(this));
                connectToCompany(companies[index]);
                return Event.stopEvent(e);
            });
        } else {
            Elements.pagetitle.hide();
            connectToCompany(companies[0]);
        }
    });

    var connectToCompany = function(company) {
        pageContainer.hide();
        app.showLoadingScreen();

        var username = self.AuthData.username;
        var password = self.AuthData.password;
        var server = self.AuthData.server;
        var companyCode = company.Cod;
        var selectedRole = "ALL";
        var liso = authData.liso || app.User.Settings.Language;
        var applicationVersion = app.MobileApplicationVersion;
        var useSAAS = authData.isSAAS;
        var companyId = company.Id || Utils.getEmptyGuid();
        var appId = Utils.getEmptyGuid();
        var prsId = 0;
        var popId = 0;
        var userId = Utils.getEmptyGuid();
        var profileId = Utils.getEmptyGuid();
        var personGuid = Utils.getEmptyGuid();

        if (authData.isSAAS) {
            app.TMMService.Redirect.GetConnectionData(server, username, password, companyId, liso, function(response) {
                if (response.Exception) {
                    app.goBack();
                    app.MessagesFactory.showError(translate('Authentication_Failed'));
                    return;
                }

                for (var key in response) {
                    if (key == "company_code")
                        companyCode = response[key];
                    else if (key == "app_id")
                        appId = response[key];
                    else if (key == "PRS_ID")
                        prsId = response[key];
                    else if (key == "POP_ID")
                        popId = response[key];
                    else if (key == "user_id")
                        userId = response[key];
                    else if (key == "profileId")
                        profileId = response[key];
                    else if (key == "PRS_GUID")
                        personGuid = response[key];
                    else if (key == "liso")
                        liso = response[key];
                }

                connectToRSServices(company, username, password, companyCode, selectedRole, liso, applicationVersion, useSAAS, companyId, prsId, popId, userId, profileId, appId, personGuid);
            });
        } else {
            connectToRSServices(company, username, password, companyCode, selectedRole, liso, applicationVersion, useSAAS, companyId, prsId, popId, userId, profileId, appId, personGuid);
        }
    };

    var connectToRSServices = function(company, username, password, companyCode, selectedRole, liso, applicationVersion, useSAAS, companyId, prsId, popId, userId, profileId, appId, personGuid) {
        app.TMMService.Security.Connect(username, password, companyCode, selectedRole, liso, applicationVersion, useSAAS, companyId, prsId, popId, userId, profileId, appId, personGuid, function (response) {
            app.hideLoadingScreen();
            if (!response || response.Exception) {
                var message = response.Exception.Message || translate('Authentication_Failed');
                app.MessagesFactory.showError(message, function () { app.disconnect(); });
                return;
            }

            response.FinalResult.ServerUrl = app.TMMService.Security.getServerUrl();
            response.FinalResult.Password = self.AuthData.password;
            response.FinalResult.Server = self.AuthData.server;
            app.setAuthenticationData(response.FinalResult);

            if (response.FinalResult.Language && response.FinalResult.Language != app.User.Settings.Language) {
                document.location.reload();
                return;
            }

            app.getCompanyDictionary(function () {
                if (!app.User.DeviceId) {
                    app.User.DeviceId = app.Phone.getDeviceId();
                    app.registerDeviceId();
                } else {
                    setTimeout(function() {
                        var mobilePlatform = app.Phone.getMobilePlatformIndex();
                        app.TMMService.PushMessaging.RegisterDevice(app.User.DeviceId, mobilePlatform, Constants.ApplicationId, app.User.Company, app.User.Username, app.User.PRS_ID, app.getCurrentSettings().Language);
                    }, 10);
                }

                app.User.CompanyPicUrl = company.POZA;

                if (connected)
                    $(document).trigger('changedCompany');

                goToDashboard();

                $.jStorage.set("lastUser", { Username: self.AuthData.username, Server: self.AuthData.server });
            });
        });
    };

    var goToDashboard = function() {
        app.TMMService.TMM.GetTMMData(function(response) {
            if (response.Exception) {
                app.setAuthenticationData(null);
                document.location.reload();
            } else {
                connected = true;
                app.TMMData = response.FinalResult;
                app.Pages.Dashboard.instance = new Dashboard(app.Pages.Dashboard.container);
                app.changePage(app.Pages.Dashboard);
            }
        });
    };

    this.canNavigate = function() {
        return !(app.TMMService.Security.getToken() || "").length || companies.length > 1;
    };

    this.goBack = function() {
        if (connected)
            app.changePage(app.Pages.Dashboard);
        else app.changePage(app.Pages.Authentication);
    };

    self.initialize();
};
extend(CompanyConnectionPage, TMMobilePage);